<?php
namespace app\manage\controller;
use app\manage\controller\Conn;
use app\manage\model\Ti as Timodel;
use think\Db;

class Ti extends Conn
{
	//这里用前置操作，表示提前运行，本来要用于栏目删除子栏目呢，现在不用了
	protected $beforeActionList = [
        
    ];
    public function index()
    {
    	$ti=new Timodel();
    	$key=input('key') ? input('key') : '';
    	$this->assign('key',$key);
		
		$ti=$ti->where('name|phone','like','%'.$key.'%')->order('id desc')->paginate(10,false,['query'=>request()->param()])->each(function($item, $key){
			$u=Db::name('user')->where('id',$item->uid)->find();
			$item->name = $u['name'];
			$item->phone=$u['phone'];
		});
		$this->assign('ti',$ti);
    	
		$count1=Db::name('ti')->count();
		$this->assign('count1', $count1);
       	return $this->fetch();
    }
	public function ajax()
    {
    	$data=input('param.');
		$ti=new Timodel();

		if($data['type']=='ti_sort'){
			$arrlength=count($data['id']);
			$ar=[];
			for($x=0;$x<$arrlength;$x++)
			{
			    $ar[$x]=['id'=>$data['id'][$x], 'sort'=>$data['sort'][$x]];
			}
			$info=$ti->saveAll($ar);
			if($info){
				return 1;
			}else{
				return 0;
			}
		}
		if($data['type']=='ti_start'){
		    if(Db::name('ti')->where('id',$data['id'])->setField('isopen',1)){
		        return 1;//修改成功返回1
		    }else{
		        return 0;
		    }
		}
		if($data['type']=='ti_stop'){
		    if(Db::name('ti')->where('id',$data['id'])->setField('isopen',0)){
		        return 1;//修改成功返回1
		    }else{
		        return 0;
		    }
		}
	
		
		
		return 0;
    }
	public function add()
    {
    	if(request()->isPost()){
			$data=input('post.');
			$validate = new \app\manage\validate\Ti;
			if(!$validate->check($data)){
				$this->error($validate->getError());
			}	
			
			$ti=new Timodel();
			$ti->data($data);
			$res=$ti->save();
			if($res){
				return $this->success('添加成功',url('ti/index',['st'=>1]));
			}else{
				$this->error('添加失败了');
			}
    	}
       return $this->fetch();
    }
	public function edit()
    {
    	$ti = new Timodel();
    	if(request()->isPost()){
    		$data=input('post.');
			if(!isset($data['type'])){
				$this->error('请选择类型');
			}
			$titype=preg_replace("/(\s|\&nbsp\;|　|\xc2\xa0)/", "", $data['ti']);
			if($data['type']==3){
				if(Db::name('ti')->where('id',$data['id'])->value('type')==3){
					$this->error('已经驳回');
				}
				
				Db::name('ti')->where('id',$data['id'])->update([
					'type'=>3
				]);
				$this->success('修改成功',url('ti/index',['st'=>1]));
			}
			if($data['type']==2){
				if(Db::name('ti')->where('id',$data['id'])->value('type')==2){
					$this->error('不能重复提现');
				}
				if(Db::name('ti')->where('id',$data['id'])->value('type')==3){
					$this->error('已经驳回');
				}
				
				$lei=\trim($data['ti']);
                $ti=Db::name('ti')->where('id',$data['id'])->find();
                $user=Db::name('user')->where('id',$ti['uid'])->find();
                if($user['money'] < $data['money']){
                    $this->error('余额不足不能提现！');
                }else{
					if($lei=='支付宝提交'){
						$this->error('支付宝尚未开通');
						Db::name('ti')->where('id',$data['id'])->update([
						    'type'=>2,
						    'true_money'=>$data['money']
						]);
						//减去 钱
						Db::name('user')->where('id',$user['id'])->setDec('money', $data['money']);
						$this->success('提现成功',url('ti/index',['st'=>1]));
					}
					
					if($lei=='手动提交'){
						//  手动提现
						Db::name('ti')->where('id',$data['id'])->update([
						    'type'=>2,
						    'true_money'=>$data['money']
						]);
						//减去 钱
						Db::name('user')->where('id',$user['id'])->setDec('money', $data['money']);
						$this->success('提现成功',url('ti/index',['st'=>1]));
					}
                    
                }
			}
    	}
		
		$id=input('id');
		$data= $ti->get($id);
		$this->assign('data',$data);
		$this->assign('shield',Db::name('shield')->find(1));
       return $this->fetch();
    }
	
	
	public function edit_bei() //这个是支付宝提现
	{
		$ti = new Timodel();
		if(request()->isPost()){
			$data=input('post.');
			if(!isset($data['type'])){
				$this->error('请选择类型');
			}
			$titype=preg_replace("/(\s|\&nbsp\;|　|\xc2\xa0)/", "", $data['ti']);
			if($data['type']==3){
				if(Db::name('ti')->where('id',$data['id'])->value('type')==3){
					$this->error('已经驳回');
				}
				
				Db::name('ti')->where('id',$data['id'])->update([
					'type'=>3
				]);
				$this->success('修改成功',url('ti/index',['st'=>1]));
			}
			if($data['type']==2){
				if(Db::name('ti')->where('id',$data['id'])->value('type')==2){
					$this->error('不能重复提现');
				}
				if(Db::name('ti')->where('id',$data['id'])->value('type')==3){
					$this->error('已经驳回');
				}
				
			
				
				include_once env('extend_path').'alipay/aop/AopCertClient.php';
				include_once env('extend_path').'alipay/aop/request/AlipayFundTransUniTransferRequest.php';
				
				$aop = new \AopCertClient ();
				$config = config('zfb_pay');
				$appCertPath = env('root_path')."zhengshu/appCertPublicKey_2021003142630159.crt";
				$alipayCertPath = env('root_path')."zhengshu/alipayCertPublicKey_RSA2.crt";
				$rootCertPath = env('root_path')."zhengshu/alipayRootCert.crt";
				$aop->gatewayUrl = 'https://openapi.alipay.com/gateway.do';
				$aop->appId = $config['appid'];
				$siyao=file_get_contents("/www/wwwroot/alg2022.bjalexu.com/zhengshu/alg.bjalexu.com.txt"); 
				$aop->rsaPrivateKey = $siyao;
				$aop->alipayrsaPublicKey = $aop->getPublicKey($alipayCertPath);//调用getPublicKey从支付宝公钥证书中提取公钥
				$aop->apiVersion = '1.0';
				$aop->signType = 'RSA2';
				$aop->postCharset='utf-8';
				$aop->format='json';
				$aop->isCheckAlipayPublicCert = true;//是否校验自动下载的支付宝公钥证书，如果开启校验要保证支付宝根证书在有效期内
				$aop->appCertSN = $aop->getCertSN($appCertPath);//调用getCertSN获取证书序列号
				$aop->alipayRootCertSN = $aop->getRootCertSN($rootCertPath);//调用getRootCertSN获取支付宝根证书序列号
				$order=Db::name('ti')->find($data['id']);
				$shield=Db::name('shield')->find(1);
				$money=$data['money'];
				
				$request = new \AlipayFundTransUniTransferRequest();
				$body = array(
						'out_biz_no'=>$order['order_id'],
						'trans_amount'=>(float)$money,
						'product_code'=>'TRANS_ACCOUNT_NO_PWD',
						'order_title'=>'官方转账提现！',
						'biz_scene'=>'DIRECT_TRANSFER',
						'payee_info'=>[
							'identity'=>$order['phone'],
							'identity_type'=>'ALIPAY_LOGON_ID',
							'name'=>$order['name'],
						]
					);
				 $request->setBizContent(json_encode($body, JSON_UNESCAPED_UNICODE));	
				//$request->setNotifyUrl($config['ali_dongjie_notify_url']); //请求成功后的回调地址
				//$result = $aop->sdkexecute ($request);
				$result = $aop->execute ( $request); 
				$array = json_decode(json_encode($result),TRUE);
				if(isset($array["alipay_fund_trans_uni_transfer_response"]) and $array["alipay_fund_trans_uni_transfer_response"]["code"]==10000 and $array["alipay_fund_trans_uni_transfer_response"]["msg"]=='Success'){
			
					$w=$array["alipay_fund_trans_uni_transfer_response"];
					//支付成功
					Db::name('ti')->where('id',$data['id'])->update([
						'type'=>2,
						'order_id_zfb'=>$w['order_id'],
						'out_biz_no'=>$w['out_biz_no'],
						'pay_fund_order_id'=>$w['pay_fund_order_id'],
						'true_money'=>$money
					]);
					//提现 alg
					$ti=Db::name('ti')->where('id',$data['id'])->find();
	
					Db::name('user')->where('id',$ti['uid'])->setDec('yuanbao', $ti['money']);
					Db::name('user')->where('id',$ti['uid'])->setDec('yue_yuanbao', $ti['money']);
					Db::name('yuanbao')->insert([
						'uid'=>$ti['uid'],
						'num'=>$ti['money'],
						'time'=>time(),
						'type'=>4,
						'order_id'=>$data['id'],
						
					]);
					$this->success('提现成功',url('ti/index',['st'=>1]));
				}else{
					$this->error('提现失败');
				}
			}
		}
		
		$id=input('id');
		$data= $ti->get($id);
		$this->assign('data',$data);
		$this->assign('shield',Db::name('shield')->find(1));
	   return $this->fetch();
	}
}
